package com.huanzhidadi.single.threadlocal;

import org.springframework.util.StopWatch;

public class ThreadContentSynchronized {

    private String content;

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public static void main(String[] args) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("同步机制");
        ThreadContentSynchronized contentSynchronized = new ThreadContentSynchronized();
        for (int i=0; i<6; i++) {
            new Thread(() -> {
                // 同步机制采用以时间换空间的方式，只提供了一份变量，让不同的线程排队访问 ThreadLocalTest2 Object都可以
                synchronized (ThreadContentSynchronized.class) {
                    contentSynchronized.setContent(Thread.currentThread().getName() + "的数据");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "\t  " + contentSynchronized.getContent());
                }
            }, String.valueOf(i)).start();
        }
        // 所有线程累加完成后输出 如果除了主线程外还有子线程存在，则主线程让出执行时间
        while (Thread.activeCount() > 2) Thread.yield();
        stopWatch.stop();
        System.out.println(stopWatch.getTotalTimeMillis() + "ms");
    }
}
